import qs from 'qs'
// const baseURL = import.meta.env.DEV ? 'https://www.icu007.top' : 'https://chat.xjtlu.edu.cn'
const baseURL = import.meta.env.DEV ? '' : 'https://xipuai.xjtlu.edu.cn'

import useUserStore from '@/stores/user'

export async function post(url, data) {
  const abortCtrl = new AbortController()
  try {
    const result = await fetch(`${baseURL}${url}`, {
      signal: abortCtrl.signal,
      method: "post",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data),
    })

    const reader = result.body.getReader()
    const decoder = new TextDecoder("utf-8")
    const { done, value } = await reader.read()
    const str = decoder.decode(value)

    return {
      status: 0,
      data: JSON.parse(str),
      message: 'success',
      abortCtrl
    }
  } catch (error) {
    abortCtrl.abort()
    return {
      status: 1,
      message: error,
    }
  }
}

export function steam(url, data) {
  const abortCtrl = new AbortController()
  return new Promise(async (resolve, reject) => {
    try {
      const res = await fetch(`${baseURL}${url}`, {
        signal: abortCtrl.signal,
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data),
      })
      // console.log('fecth', res)
      let _data
      const contentType = res.headers.get('content-type')
      const isStream = contentType.indexOf('text/event-stream') !== -1
      if (isStream) {
        _data = await res.text()
      } else {
        _data = await res.json()
        const { code, data, msg } = _data
        if (code == -1) {
          console.log('用户未登录')
          if (data.jumpUrl) {
            const { clear } = useUserStore()
            clear()
            location.href = data.jumpUrl
          }
        }
      }
      // console.log(11, _data, res)

      resolve({
        status: 0,
        data: _data,
        message: 'success',
        abortCtrl
      })
    } catch (error) {
      abortCtrl.abort()
      reject({
        status: 1,
        message: error,
      })
    }
  })
}

// setTimeout(() => {
//   abortCtrl.abort()
//   console.log('停止请求')
// }, 1000)

export default { post, steam }

export async function api_hww(messages, params = {}) {
  try {
    const result = await fetch('https://www.icu007.top/testai/streamai.php', {
      method: "post",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        stream: true,
        ...params,
        messages
      }),
    })
    return {
      status: 0,
      data: result.body,
      message: 'success'
    };
  } catch (error) {
    return {
      status: 1,
      message: error,
    }
  }
}